from rest_framework import viewsets, status
from rest_framework.response import Response
from rest_framework.decorators import action

from user.serializers import UserSerializer, RoleSerializer, ClazzSerializer
from user.models import User, Role, Clazz


class UserViewSet(viewsets.GenericViewSet):

    queryset = User.objects.filter(is_delete=False)

    serializer_class = UserSerializer

    def create(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return Response(serializer.data, status=status.HTTP_201_CREATED)

    @action(methods=['GET'], detail=False, url_path='find_role_class_list', url_name='find_role_class_list')
    def find_role_class_list(self, request, *args, **kwargs):

        # 查询所有角色信息
        roles_queryset = Role.objects.filter(is_delete=False, state=True)

        # 查询所有班级信息
        class_queryset = Clazz.objects.filter(is_delete=False, state=True)

        roles_serializer = RoleSerializer(roles_queryset, many=True, fields=['id', 'name'])

        class_serializer = ClazzSerializer(class_queryset, many=True, fields=['id', 'name'])

        data = {
            'roleList': roles_serializer.data,
            'clazzList': class_serializer.data
        }

        return Response(data, status=status.HTTP_200_OK)

    # 查询所有角色信息
    @action(['GET'], detail=False, url_path='find_user_list', url_name='find_user_list')
    def find_user_list(self, request, *args, **kwargs):

        users = User.objects.filter(is_delete=False, is_active=True)
        users_serializer = UserSerializer(users, many=True)
        return Response(users_serializer.data, status=status.HTTP_200_OK)
